package cn.openread.demo.multithread.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 队列同步器 AbstractQueuedSynchronizer（以下简称同步器）
 * java.util.concurrent.locks.AbstractQueuedSynchronizer#acquire 独占式获取同步状态
 * java.util.concurrent.locks.AbstractQueuedSynchronizer#acquireInterruptibly 独占式获取同步状态，未可以 独占式获取同步状态，未可以 独占式获取同步状态，未可以 中断
 * java.util.concurrent.locks.AbstractQueuedSynchronizer#acquireShared共享式获取同步状态
 * java.util.concurrent.locks.AbstractQueuedSynchronizer#acquireSharedInterruptibly共享式获 取同步状态，未共享式获 取同步状态，未取可以中断
 * java.util.concurrent.locks.AbstractQueuedSynchronizer#release独占释放锁 独占释放锁
 * java.util.concurrent.locks.AbstractQueuedSynchronizer#releaseShared共
 */
public class ReentrantLock01 {
    private static final ReentrantLock reentrantLock = new ReentrantLock();
    static int i = 0;

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock01 reentrantLock01 = new ReentrantLock01();
        new Thread(() -> {
            reentrantLock01.add();
        }).start();
        Thread.sleep(1000);//主要目的是让两个线程把事情干完
        new Thread(() -> {
            reentrantLock01.add();
        }).start();
        Thread.sleep(1000);//主要目的是让两个线程把事情干完
        System.out.println(i);

    }

    /***
     * 强调try fianlly规范
     */
    public void add() {
        try {
            reentrantLock.lock();
            for (int j = 0; j < 10000; j++) {
                i++;
            }
        } finally {
            reentrantLock.unlock();
        }
    }


}
